package com.example.demo.gateway.config;

import com.example.demo.gateway.core.exception.GlobalExceptionHandler;
import com.example.demo.response.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: miaoguoxin
 * @Date: 2018/12/12 21:53
 * @Description:全局异常bean配置
 */
@Configuration
@Slf4j
public class ExceptionConfiguration {
   // @Primary
   // @Bean
   // @Order(Ordered.HIGHEST_PRECEDENCE)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                                             ServerCodecConfigurer serverCodecConfigurer) {
        GlobalExceptionHandler jsonExceptionHandler = new GlobalExceptionHandler();
        jsonExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
        jsonExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
        jsonExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
        return jsonExceptionHandler;
    }

    @Bean
    public DefaultErrorAttributes defaultErrorAttributes(){
        return new DefaultErrorAttributes(){
            @Override
            public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
                Map<String, Object> errorAttributes = super.getErrorAttributes(request, includeStackTrace);
                Map<String,Object> newResult = new LinkedHashMap<>();
                newResult.put("message",errorAttributes.get("error"));
                newResult.put("code",errorAttributes.get("status"));
                return newResult;
            }

            @Override
            public Throwable getError(ServerRequest request) {
                Throwable error = super.getError(request);
                log.error("异常",error);
                return error;
            }
        };
    }

}
